package cn.ucox.web.ms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;

/**
 * 应用程序启动监听
 * <br>当监控到应用程序启动或关闭或会分别调用数据交换程序start及stop方法
 *
 * @author chenw
 * @create 2017-07-28 20:03
 * @email javacspring@gmail.com
 */
public class BootstrapListener implements ApplicationListener {

    public static final Logger logger = LoggerFactory.getLogger(BootstrapListener.class);

    private DexBootstrap bootstrap;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量
            logger.debug("ApplicationEnvironmentPreparedEvent");
        } else if (event instanceof ApplicationStartingEvent) {
            logger.debug("ApplicationStartingEvent");
        } else if (event instanceof ApplicationPreparedEvent) { // 初始化完成
            logger.debug("ApplicationPreparedEvent");
        } else if (event instanceof ContextRefreshedEvent) { // 应用刷新
            logger.debug("ContextRefreshedEvent");
        } else if (event instanceof EmbeddedServletContainerInitializedEvent) {
            logger.debug("EmbeddedServletContainerInitializedEvent");//内嵌tomcat初始化完成，端口监听开始
        } else if (event instanceof ApplicationReadyEvent) {// 应用已启动完成
            logger.debug("ApplicationReadyEvent");
            bootstrap = new DexBootstrap(((ApplicationReadyEvent) event).getApplicationContext());
            bootstrap.start();
        } else if (event instanceof ContextStartedEvent) { //应用启动，需要在代码动态添加监听器才可捕获
            logger.debug("ContextStartedEvent");
        } else if (event instanceof ContextStoppedEvent) { // 应用停止
            logger.debug("ContextStoppedEvent");
        } else if (event instanceof ContextClosedEvent) { // 应用关闭
            logger.debug("ContextClosedEvent");
            bootstrap.stop();
        } else {
            logger.debug("other event~");
        }
    }
}